/**
 *  FPUStack.java : IceBird project
 *  13:44:20 
 */
package icebird.compiler.x86.old;

import icebird.compiler.x86.old.X86Register.FPU;

/**
 * Represents FPU stack(Stack of floating point
 * registers).
 * @author Sergey Shulepoff[Knott]
 */
public final class FPUStack extends ItemStack {
	
	private static final FPU[] REGS = new FPU[] {
		X86Register.ST0, X86Register.ST1,
		X86Register.ST2, X86Register.ST3,
		X86Register.ST4, X86Register.ST5,
		X86Register.ST6, X86Register.ST7
	};
	
	public FPUStack() {
		super(REGS.length);
	}
	
	/**
	 * Gets register.
	 * @return FPU
	 */
	public final FPU getRegister(Item item) {
		for (int i = 0; i < peek; i++) {
			if (stack[peek - (i + 1)] == item) {
				return REGS[i];
			}
		}
		throw new RuntimeException("Item not found on FPU stack");
	}
	
	/**
	 * Get item.
	 * @return Item
	 */
	public final Item getItem(FPU fpu) {
		return stack[peek - (getNr(fpu) + 1)];
	}
	
	public final void fxch(FPU reg) {
		int idx1 = peek - 1;
		int idx2 = peek - (getNr(reg) + 1);
		
		Item tmp = stack[idx1];
		stack[idx1] = stack[idx2];
		stack[idx2] = tmp;
	}
	
	private int getNr(FPU f) {
		int nr = 0;
		for (int i = 0; i < REGS.length; i++) {
			if (REGS[i] == f) {
				nr++;
				continue;
			}
		}
		
		return nr;
	}
}
